/*
 * @Author: your name
 * @Date: 2021-05-08 10:02:38
 * @LastEditTime: 2021-05-12 13:09:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \after-end\app\service\user.js
 */
const Service = require('egg').Service;
const { v1 } = require('uuid');
const { SuccessModel, FailModel } = require('../resModel');
const { getPassword } = require('../extends/crypto');
const jwt = require('jsonwebtoken');

class UserService extends Service {

    //后台管理用户注册
    async regisert() {
        const { ctx, app } = this;
        const { ipId, phone, password, nickname, avatar } = ctx.request.body;
        const userId = v1();
        const findData = await app.mysql.query(`select * from userTable where phone=?`, [phone]);
        if (findData.length) {
            return await new FailModel("用户存在");
        } else {
            const insertData = await app.mysql.query(`insert into userTable (userId,ipId, phone, password, nickname, avatar) values (?,?,?,?,?,?)`, [userId, ipId, phone, getPassword(password), nickname, avatar]);
            if (insertData.affectedRows) {
                return await new SuccessModel("Success");
            }
            return await new FailModel("Failed");
        }
    }

    //后台管理用户登录
    async login() {
        const { ctx, app } = this;
        const { phone, password } = ctx.request.body;
        const findData = await app.mysql.query(`select * from userTable where phone=? and password=?`, [phone, getPassword(password)]);
        const token = jwt.sign({ ...findData }, app.config.keys, { expiresIn: '24h' });
        if (findData.length) {
            return await new SuccessModel({
                token, data: {
                    ipId: findData[0].ipId,
                    phone: findData[0].phone,
                    nickname: findData[0].nickname,
                    avatar: findData[0].avatar,
                }
            }, "Success");
        } else {
            return await new FailModel("Failed");
        }
    }

    //后台管理用户列表
    async fandUserTable() {
        const { app } = this;
        const findData = await app.mysql.query(`select * from userTable `);
        if (findData.length) {
            return await new SuccessModel({ findData, code: 200 }, "Success");
        } else {
            return await new FailModel("Failed");
        }
    }

}

module.exports = UserService;